<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2017-12-22
 * Time: 下午 10:30
 */
error_reporting(E_ALL ^ E_NOTICE);
require_once 'JKWebSocket.php';

const ROOM_ID = 'room_id';
const ROOMS = 'rooms';

$server = new JKWebSocket(8800);
// $server->config('recv_mode', JKSocket::RECV_MODE_BIN);

$server->onListen(function($obj, $args) {
    echo "Listen ..\n";
});

$server->onConnect(function (JKWebSocket $server, JKWebSocketArgument $event){
    /** @var JKWebSocket $client */
    $client = $event->getClient();
    $roomId = mt_rand(0, 2);
    $client->set(ROOM_ID, $roomId);
    $date = date('Y-m-d H:i:s');
    $server->setKeyArrayValue(ROOMS, $roomId, $client->getIndex(), $client);
    
    echo "[$date] New clinet #{$client->getIndex()} ({$client->getAddr()}) connected, room $roomId\n";
    // $client->send("Enter room $roomId, ID in server:{$client->getIndex()}\r\n");
});

$server->onClose(function (JKWebSocket $server, JKWebSocketArgument $event) {
    /** @var JKWebSocket $client */
    $client = $event->getClient();
    $roomId = $client->get(ROOM_ID);
    $date = date('Y-m-d H:i:s');
    $server->removeKeyArrayValue(ROOMS, $roomId, $client->getIndex());
    echo "[$date] Clinet #{$client->getIndex()} ({$client->getAddr()}) closed, room $roomId\n";
});

$server->onRecv(function (JKWebSocket $server, JKWebSocketArgument $event) {
    /** @var JKWebSocket $client */
    $client = $event->getClient();
    $data = $event->getData();
    echo "Recv from #{$client->getIndex()} ({$client->getAddr()}): $data\n";
    echo "Server send\n";
    $client->send("LEN(".strlen($data).") content:" . $data);
});

if($server->listen()->fail()) {
    echo $server->getLastError();
}